package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {


    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("新增分类成功");
        categoryService.save(category);
        return R.success(category.getType() == 1 ? "添加菜品分类成功":"添加套餐分类成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        //条件构造器
        Page pageInfo = new Page(page,pageSize);

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.orderByAsc(Category::getSort);

        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    @DeleteMapping
    public R<String> deleteById(Long ids){//这里参数名ids要和前端axios发送的参数名ids一致，否则删除就会失败
        log.info("将被删除的id：{}", ids);
        categoryService.remove(ids);
        return R.success("删除成功");
    }

    //category并没有实现回显的函数，因为回显数据在前端存储了，回显直接由前端实现了
    //修改分类
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("分类修改成功");
        categoryService.updateById(category);
        return R.success("分类修改成功");
    }

    //根据type查询菜品分类
    @GetMapping("/list")
    public R<List<Category>> list(Category category){//注意这里不能用@RequestBody Category category，前面axios发送请求时没用data:params的格式，而是只用了params，因此应该是没JSON格式，所以这里不能加@RequestBody

        //创建条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        //加上条件
        queryWrapper.eq(category.getType() != null,Category::getType,category.getType());

        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);

        return R.success(list);
    }

}
